package leetcodecompetition.D360;

import java.util.List;

/**
 * @Author: Siantar
 * @Date: 2023-08-27-10:51
 * @Description: 1.0
 */
public class T8021 {
    public int minOperations(List<Integer> nums, int target) {
        int[] arr = new int[31];
        for (int num : nums) {
            arr[f(num)]++;
        }
        int s = 0;
        for (int i = 0; i <= 30; i++) {
            if ((target & (1 << i)) > 0) {
                System.out.println((1 << i));
                if (arr[i] > 0) arr[i]--;
                else s += Math.pow(2, i);
            }
        }
        System.out.println(s);
        int res = 0, r = 0;
        for (int i = 0; i <= 30; i++) {
            r += arr[i] * (1 << i);
            if ((s & (1 << i)) > 0) {
                if (r >= (1 << i)) {
                    r -= (1 << i);
                    continue;
                }
                int j = i + 1;
                while (j <= 30 && arr[j] == 0) {
                    arr[j]++;
                    j++;
                }
                if (j == 31) return -1;
                arr[j]--;
                res += j - i;
                r += (1 << i);
            }
        }
        return res;
    }

    public int f(int num) {
        int res = 0;
        while (num != 1) {
            num /= 2;
            res++;
        }
        return res;
    }
}
